#include "stringtokenizer.h"

namespace MCCommon
{

static const int kStartPos = 0;

StringTokenizer::StringTokenizer()
:   fDelim( ";"),
    fCurSubStrPos( kStartPos )
{
}

StringTokenizer::StringTokenizer
(
    const std::string& str,
    const std::string& delim/* = ";"*/
)
:   fDelim( delim ),
    fCurSubStrPos( kStartPos ),
    fString( str )
{
}

StringTokenizer::~StringTokenizer()
{
}

bool
StringTokenizer::HasMore() const
{
    bool hasMore( true );

    if ( fCurSubStrPos == std::string::npos ||
        fCurSubStrPos >= (int)fString.size() )
    {
        hasMore = false;
    }
    
    return hasMore;
}

std::string
StringTokenizer::NextToken() const
{
    std::string token;

    int curPos = fCurSubStrPos;

    fCurSubStrPos = fString.find( fDelim, fCurSubStrPos );
    if ( fCurSubStrPos != std::string::npos )
    {
        int count = fCurSubStrPos-curPos;
        token = fString.substr( curPos, count );
        fCurSubStrPos += fDelim.size();
    }
    else if ( curPos < fString.size() )
    {
        int count = fString.size()-curPos;

        token = fString.substr( curPos, count );
    }

    return token;
}

void
StringTokenizer::Rewind() const
{
    fCurSubStrPos = kStartPos;
}

void
StringTokenizer::SetDelimiter
( 
    const std::string& delim
)
{
    fDelim = delim;
}

void 
StringTokenizer::SetTokenString
( 
    const std::string& tokenString,
    const std::string& delim/* = ";"*/  
)
{
    fString = tokenString;
    fDelim = delim;

    Rewind();
}

void ArrayToString
(
    const std::vector< std::string >& arrStr,
    std::string& tokenString,
    const std::string& delim/* =";"*/
)
{
    tokenString = "";
    for ( int i=0; i< (int)arrStr.size(); i++ )
    {
        tokenString += arrStr[i] + delim;
    }
}

void StringToArray
(
    const std::string& tokenString,
    std::vector< std::string >& arrStr, 
    const std::string& delim/* =";" */ 
)
{
    arrStr.clear();

    StringTokenizer token( tokenString, delim );    
    while ( token.HasMore() )
    {
        arrStr.push_back( token.NextToken() );
    }
}

} // end of namespace MCCommon.
